<template>
  <div class="DialogAddUser">
    <el-dialog title="添加用户" :visible.sync="visible">
      <el-form
        :model="userForm"
        :rules="rules"
        ref="ruleForm"
        label-width="65px"
        class="demo-ruleForm"
        label-position="right"
      >
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          :on-change="imgChange"
        >
          <img v-if="avatar" :src="avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form-item label="用户名" prop="mg_name">
          <el-input v-model="userForm.mg_name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="mg_pwd">
          <el-input v-model="userForm.mg_pwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mg_email">
          <el-input v-model="userForm.mg_email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mg_mobile">
          <el-input v-model="userForm.mg_mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()" :loading="loadingFlag"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUser } from "@/api/user";
import { mapActions, mapState } from "vuex";
export default {
  name: "DialogAddUser",
  data() {
    var check_mg_name = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (this.checkName()) {
        callback(new Error("该用户名已存在"));
      } else if (value.length < 3 || value.length > 10) {
        callback(new Error("长度在 3 到 10 个字符"));
      } else {
        //这个必须写 必须具备else
        callback();
      }
    };
    return {
      visible: false,
      userForm: {
        mg_name: "",
        mg_pwd: "",
        mg_email: "",
        mg_mobile: "",
        mg_avatar: "",
      },
      avatar: "",
      loadingFlag: false,
      rules: {
        //这个是自定义的检测 （用户名可能已经存在）
        mg_name: [
          { required: true, validator: check_mg_name, trigger: "blur" },
        ],
        mg_pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        mg_email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        mg_mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern:
              /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "请输入正确的号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.$bus.$on("visibleAddUser", (flag) => {
      this.visible = flag;
      //清除之前的内容
      Object.assign(this.$data.userForm, this.$options.data().userForm);
      this.avatar = "";
      this.$nextTick(() => {
        this.$refs["ruleForm"] && this.$refs["ruleForm"].clearValidate();
      });
    });
  },
  computed: {
    ...mapState("userStore", ["userList"]),
  },
  methods: {
    ...mapActions("userStore", ["get_user_list"]),
    checkName() {
      let nameRecept = this.userList.some((item) => {
        if (item.mg_name === this.userForm.mg_name) {
          return true;
        }
      });
      return nameRecept;
    },
    addUser() {
      this.loadingFlag = true;
      // console.log(this.$refs["ruleForm"].validate());
      this.$refs["ruleForm"].validate((valid) => {
        // console.log("valid=", valid);
        if (valid) {
          // 验证通过
          let fd = new FormData();
          Object.keys(this.userForm).forEach((key) => {
            fd.append(key, this.userForm[key]);
          });
          addUser(fd).then(
            (res) => {
              // console.log(res.data);
              //添加成功，刷新页面（等价于再次请求userList）
              this.get_user_list();
              this.visible = false; //关闭dialog
              this.loadingFlag = false; //不再加载
              //提示框
              this.$message({
                message: "添加成功!",
                type: "success",
              });
            },
            (err) => {
              console.log(err);
              this.loadingFlag = false;
              his.loadingFlag = false; //不再加载
            }
          );
        }
      });
    },
    imgChange(file, fileList) {
      // console.log(file.raw.type);
      const ImgForm =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size < 1024 * 1024 * 2; //小于2M

      if (!ImgForm)
        return this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      if (!isLt2M) return this.$message.error("上传头像图片大小不能超过 2MB !");

      //得到本地图像(详细见md)
      this.avatar = URL.createObjectURL(file.raw);
      this.userForm.mg_avatar = file.raw;
    },
  },
};
</script>

<style  scoped>
::v-deep .el-dialog__body {
  padding: 10px 20px 0;
}
.avatar-uploader {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 150px !important;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  border: 1px dashed #c6c2c2;
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  width: 128px;
  height: 128px;
  display: block;
}
</style>
